<template>
  <div>
    <el-row type="flex" :gutter="10" class="row-bg">
      <el-col :span="5">
        <div style="margin-top: 15px">
          <el-tree
            ref="tree"
            :props="props1"
            :data="data"
            node-key="id"
            :expand-on-click-node="false"
            @node-click="select">
      <span class="custom-tree-node" slot-scope="{ node, data }" v-on:mouseenter="showEdit(node)"
            v-on:mouseleave="hideEdit(node)">
          <span style="display: inline-block;padding-right: 30px"><icon-svg name="fileopen"></icon-svg>&nbsp;<span v-if="node.data.select" style="color: red">{{ node.label}}</span><span
            v-if="!node.data.select">{{ node.label}}</span></span>
        <span v-if="node.data.s_edit">
            <i style="color: #00a65a" class="el-icon-plus" @click="() => addNode(node)"></i>
            <i style="color: #286aa6" class="el-icon-edit" @click="() => edit(node)"></i>
            <i v-if="node.data.pid != 0 && node.data.children.length == 0" style="color: #a6300a" class="el-icon-delete"
               @click="() => delNode(node, data)"></i>
        </span>
      </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="19">
        <div class="mod-config">
          <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()" size="mini">
            <el-form-item label="上传用户">
              <el-select clearable
                         v-model="selectUser"
                         placeholder="选择筛选"
                         @change="getDataList"
                         @clear="getDataList"
              >
                <el-option
                  v-for="item in users"
                  :key="item.userId"
                  :label="item.username"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
            <!--<el-form-item label="审核状态">-->
              <!--<el-select clearable-->
                         <!--v-model="selectStatus"-->
                         <!--placeholder="选择筛选"-->
                         <!--@change="getDataList"-->
                         <!--@clear="getDataList"-->
              <!--&gt;-->
                <!--<el-option-->
                  <!--v-for="item in checkStatus"-->
                  <!--:key="item.value"-->
                  <!--:label="item.label"-->
                  <!--:value="item.value">-->
                <!--</el-option>-->
              <!--</el-select>-->
            <!--</el-form-item>-->
            <el-form-item>
              <!--<el-button @click="getDataList()">查询</el-button>-->
              <el-button v-if="isAuth('sys:material:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
              <el-button v-if="isAuth('sys:material:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
            </el-form-item>
          </el-form>
          <el-table
            size="small"
            :data="dataList"
            border
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%;">
            <el-table-column
              fixed
              type="selection"
              header-align="center"
              align="center"
              width="50">
            </el-table-column>
            <!--<el-table-column-->
              <!--prop="id"-->
              <!--header-align="center"-->
              <!--align="center"-->
              <!--label="ID"-->
              <!--width="50">-->
            <!--</el-table-column>-->
            <el-table-column
              prop="name"
              header-align="center"
              align="center"
              label="名称">
              <template slot-scope="scope">
                <FiledEdit
                  :id="scope.row.id"
                  name="name"
                  :value="scope.row.name"
                  url="/sys/material/update"
                  @callback="getDataList">
                </FiledEdit>
              </template>
            </el-table-column>
            <el-table-column
              prop="cid"
              header-align="center"
              align="center"
              label="目录">
              <template slot-scope="scope">
                <span style="">
                  {{scope.row.cName}}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="fileName"
              header-align="center"
              align="center"
              label="文件名"
              width="100">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="left">
                  <p>{{ scope.row.fileName }}</p>
                  <div slot="reference" class="name-wrapper">
                    <span>{{ scope.row.fileName.length > 10?scope.row.fileName.substring(0,10) + '...':scope.row.fileName }}</span>
                  </div>
                </el-popover>

              </template>
            </el-table-column>
            <el-table-column
              prop="filePath"
              header-align="center"
              align="center"
              label="路径"
              width="100">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="left">
                  <p>{{ scope.row.filePath }}</p>
                  <div slot="reference" class="name-wrapper">
                    <span>{{ scope.row.filePath.length > 10?scope.row.filePath.substring(0,10) + '...':scope.row.filePath }}</span>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              prop="createUser"
              header-align="center"
              align="center"
              label="创建人">
              <template slot-scope="scope">
                <span style="">
                  {{scope.row.uName}}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              header-align="center"
              align="center"
              label="创建时间">
            </el-table-column>
            <el-table-column
              prop="fileSize"
              header-align="center"
              align="center"
              label="大小">
              <template slot-scope="scope">
                <span style="color: green">{{scope.row.fileSize/1000}}</span>KB
              </template>
            </el-table-column>
            <!--<el-table-column-->
              <!--prop="checkStatus"-->
              <!--header-align="center"-->
              <!--align="center"-->
              <!--label="审核状态">-->
              <!--<template slot-scope="scope">-->
                <!--<el-tag v-if="scope.row.checkStatus == 0" type="info" size="medium">待审核</el-tag>-->
                <!--<el-tag v-if="scope.row.checkStatus == 1"  type="warning" size="medium">测试阶段</el-tag>-->
                <!--<el-tag v-if="scope.row.checkStatus == 2"  type="danger" size="medium">审核通过</el-tag>-->
                <!--<el-tag v-if="scope.row.checkStatus == 3" type="success" size="medium">审核失败</el-tag>-->
              <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              :width="140"
              label="操作">
              <template slot-scope="scope" >
                <el-button type="text" size="small" @click="showMaterial(scope.row.filePath)">查看</el-button>
                <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
                <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
          <!-- 弹窗, 新增 / 修改 -->
          <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="新增目录" :visible.sync="showAddGroup">
      <el-form :model="curNode">
        <el-form-item label="名称" label-width="120px">
          <el-input v-model="curNode.name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddGroup = false">取 消</el-button>
        <el-button type="primary" @click="saveRoot">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="重命名" :visible.sync="showEditGroup">
      <el-form :model="curNode">
        <el-form-item label="名称" label-width="120px">
          <el-input v-model="curNode.name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditGroup = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import AddOrUpdate from './material-add-or-update'

  export default {
    data () {
      return {
        selectUser: null,
        selectStatus: null,
        users: [],
        checkStatus: [{
          value: '0',
          label: '未审核'
        }, {
          value: '1',
          label: '测试阶段'
        }, {
          value: '2',
          label: '审核通过'
        }, {
          value: '3',
          label: '审核失败'
        }],
        dataForm: {
          key: ''
        },
        props1: {
          label: 'name',
          children: 'children',
          isLeaf: 'leaf'
        },
        data: [],
        showAddGroup: false,
        showEditGroup: false,
        curNode: {},
        selectedNode: {},
        pNode: {},
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false
      }
    },
    components: {
      AddOrUpdate
    },
    activated () {
      // this.getDataList()
    },
    mounted () {
      this.getGroups()
      this.$http({
        url: this.$http.adornUrl('/sys/user/l'),
        method: 'get'

      }).then(({data}) => {
        this.users = data.data
      })
    },
    methods: {
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/sys/material/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key,
            'cid': this.selectedNode.data ? this.selectedNode.data.id : 0,
            'createUser': this.selectUser,
            'checkStatus': this.selectStatus
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        if (this.selectedNode.data == null) {
          this.$message.error('未选择目录')
          return
        }
        console.log("222222")
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          console.log("xxxx")
          this.$refs.addOrUpdate.init(id, this.selectedNode.data.id, this.getRoot(this.selectedNode))
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/sys/material/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      getGroups () {
        const self = this
        const url = '/sys/materialclass/l'
        this.$http({
          url: this.$http.adornUrl(url),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            self.data = data.data
            this.$refs.tree.setCurrentKey(1)
            self.data[0].select = true
            this.selectedNode.data = self.data[0]
            this.getDataList()
          } else {
            // alert(data.msg)
            this.$message({
              type: 'error',
              message: data.msg
            })
          }
        })
      },
      saveGroup (callback) {
        const node = this.curNode
        const url = node.id == null ? '/sys/materialclass/save' : '/sys/materialclass/update'
        this.$http({
          url: this.$http.adornUrl(url),
          method: 'post',
          data: this.$http.adornData(node)
        }).then(({data}) => {
          if (data && data.code === 0) {
            callback(data)
          } else {
            // alert(data.msg)
            this.$message({
              type: 'error',
              message: data.msg
            })
          }
        })
      },
      addRoot () {
        this.curNode = {}
        this.curNode.pid = 0
        this.showAddGroup = true
      },
      saveRoot () {
        const self = this
        this.saveGroup(function (r) {
          console.log('r', r)
          self.showAddGroup = false
          self.append(r.data)
        })
      },
      getRoot (node) {
        if (node.data.pid === 0) {
          return node.data.id
        } else {
          return this.getRoot(this.$refs.tree.getNode(node.data.pid))
        }
      },
      reload: function (event) {
        this.getDataList()
      },
      append (data) {
        data.children = []
        if (data.pid === 0) {
          this.data.push(data)
        } else {
          this.$refs.tree.append(data, this.pNode)
        }
      },
      addNode (node) {
        this.pNode = node
        this.curNode = {}
        this.curNode.pid = node.data.id
        this.showAddGroup = true
      },
      remove (node, data) {
        this.$refs.tree.remove(node)
      },
      delNode (node, data) {
        this.$confirm('此操作将永久删除该分组, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var url = '/sys/materialclass/delete/' + node.data.id
          this.$http({
            url: this.$http.adornUrl(url),
            method: 'post'
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.remove(node, data)
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: data.msg
              })
            }
          })
        }).catch(() => {
        })
      },
      edit (node) {
        this.curNode = node.data
        this.showEditGroup = true
      },
      saveEdit () {
        const self = this
        this.saveGroup(function (r) {
          self.showEditGroup = false
        })
      },
      hideEdit (node) {
        node.data.s_edit = false
        node.data.name = node.data.name.trim()
      },
      showEdit (node) {
        node.data.s_edit = true
        node.data.name = node.data.name + ' '
      },
      select (data, node, ele) {
        // console.log('key', this.$refs.tree.getCurrentKey())
        if (this.selectedNode.data) {
          // console.log(this.selectedNode)
          this.selectedNode.data.select = false
          this.selectedNode.data.name = ' ' + this.selectedNode.data.name
          this.selectedNode.data.name = this.selectedNode.data.name.trim()
        }
        data.select = true
        data.name = ' ' + node.data.name
        this.selectedNode = node
        this.getDataList()
      },
      showMaterial(path){
        window.location.href = path
      }
    }
  }
</script>
